using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using BTS.DB;
using BTS.Entity;

namespace BTS.Page
{

    public partial class AppLogin : System.Web.UI.Page
    {
        public string aaa = "AAA";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
//                Response.Redirect("Default.aspx");
                string username = Request.Params["btsuser"];
                string passwd = Request.Params["btspasswd"];
                AppUser loginUser = ValidateLogin(username, passwd);
                if (loginUser!=null)
                {
                    Session["USER"] = loginUser;
                    Response.Redirect("Default.aspx");
                }
                Response.Redirect("NoRight.aspx");
            }
            else
            {
                //  Response.Redirect("AppLogin.aspx");
            }
        }

        protected AppUser ValidateLogin(string username, string passwd)
        {
            DBManager db = new MySQLDBManager("localhost", "BTS", "root", "btsman");
            OdbcDataReader reader = null;
            try
            {
                reader = db.Query("SELECT * FROM User WHERE username='" + username + "'");
                while (reader.Read())
                {
                    AppUser user = AppUser.CreateForm(reader);
                    if (user._encodedPassword == null) return null;
                    if (user._encodedPassword.Equals(AppUser.GetMD5Encoded(passwd) ))
                        return user;
                }
                return null;
            }
            catch (Exception e) { return null; }
            finally { db.Close(reader); }                

        }

    }
}